/* 
  Copyright (c) SilverLining 2015
  Date:    2016-1-7
  File:    TextArchiver.cpp  
  Description: 

*/

#include "stdafx.h"

using namespace System;
using namespace System::Security;

#include "shim_object.h"
#include "GameObject.h"
#include "Archiver.h"
#include "TextArchiver.h"

using namespace m;
using namespace m::text;

namespace SL
{
	namespace M
	{
		namespace Text
		{
			TextArchiver::TextArchiver()
				: 
				_Buffer(new text_buffer())
			{
			}

			TextArchiver::~TextArchiver()
			{
				TextArchiver::!TextArchiver();
			}

			TextArchiver::!TextArchiver()
			{
				if (_Buffer)
				{
					_Buffer->release();
				}
			}

			String ^ TextArchiver::Archive(GameObject ^ root)
			{
				ref_storage track1;
				m::text::text_serializer* serializer = create(track1, new m::text::text_serializer());
				Archive(root, serializer);
				serializer->save(_Buffer);
				size_t outputSize = _Buffer->size() + 1; // Must include terminating null.
				if (outputSize >= INT32_MAX)
				{
					throw gcnew IndexOutOfRangeException("Size of data too large.");
				}
				wchar_t* buf = new wchar_t[outputSize];
				try
				{
					_Buffer->set_offset(0);
					_Buffer->read(buf, outputSize);

					return gcnew String(buf);
				}
				finally
				{
					delete[] buf;
				}
			}

			void TextArchiver::Unarchive(GameObject ^ root, String ^ data)
			{
				if (data == nullptr)
				{
					throw gcnew ArgumentNullException("data");
				}

				_Buffer->set_size(0);
				_Buffer->set_offset(0);
				pin_ptr<const wchar_t> dataChars = PtrToStringChars(data);
				_Buffer->write(dataChars);

				ref_storage track1;
				m::text::text_serializer* serializer = create(track1, new m::text::text_serializer());
				serializer->load(_Buffer);
				Unarchive(root, serializer);
			}
		}
	}
}